package com.niodata.dp.mybatis;

import com.niodata.dp.collection.WrappedStringMap;
import com.niodata.dp.util.JsonUtil;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class WrappedStringMapTypeHandler extends BaseTypeHandler<WrappedStringMap>
      implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGNVARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return WrappedStringMapTypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return WrappedStringMap.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int i,
        WrappedStringMap wrappedStringMap, JdbcType jdbcType) throws SQLException {
    String json = "";
    try {
      json = JsonUtil.toJson(wrappedStringMap);
    } catch (Exception e) {
      //nothing to do
    }
    preparedStatement.setString(i, json);

  }

  @Override
  public WrappedStringMap getNullableResult(ResultSet resultSet, String s) throws SQLException {
    String json = resultSet.getString(s);
    WrappedStringMap map = null;
    try {
      map = JsonUtil.fromJson(WrappedStringMap.class, json);
    } catch (Exception e) {
      //nothing to do
    }
    return map;
  }

  @Override
  public WrappedStringMap getNullableResult(ResultSet resultSet, int i) throws SQLException {
    String json = resultSet.getString(i);
    WrappedStringMap map = null;
    try {
      map = JsonUtil.fromJson(WrappedStringMap.class, json);
    } catch (Exception e) {
      //nothing to do
    }
    return map;
  }

  @Override
  public WrappedStringMap getNullableResult(CallableStatement callableStatement, int i)
        throws SQLException {
    return null;
  }
}
